import { OldageProductListModule } from "./../../list/oldage-product-list.module";
import { OldageProductModule } from "./../../oldage-product.module";
import { OldageListModule } from "./../../../oldage/list/oldage-list.module";
import { Component, OnInit } from "@angular/core";
import { InfoService } from "app/pages/oldage-product/modal/info/info.service";
import { ActivatedRoute, Router } from "@angular/router";
import { DataService } from "app/services/data.service";
import * as flatpickr from "flatpickr";
import { zh } from "flatpickr/dist/l10n/zh.js";
import { Util } from "app/common/util";
import * as _ from 'lodash';
import { AreaDataCnModule } from "../../../../widgets/area-data-cn/area-data-cn.module";
@Component({
  selector: "app-info",
  templateUrl: "./info.component.html",
  styleUrls: ["./info.component.scss"],
  providers: [InfoService]
})
export class InfoComponent implements OnInit {
  //产品代码字节长度
  public realLength: any;
  //所属地区
  public area: any;
  // 路由nFundNo
  public nFundNo: any;
  public index: any;
  // 路由operate
  public operate: any;
  // 托管人数据
  // public bankDictionaryList = [];
  // 投资经理列表
  public ManagerList;
  // 项目经理列表
  public ProjectManagerList;
  // 移交投管人
  public sInvestorSelectList: any;
  // 其他投资管理人
  public investorSelectList: any;
  // 项目经理
  public managerSelectList: any;
  // 备案机构、受托人、托管人
  public distionary: any = {
    RECORDORG_TYPE: [],  // 备案机构
    LINK_PRINCIPAL_NO: [],   //受托人
    TRUSTEE: []   //  托管人
  }
  // 获取字典值
  public dictionaryList: any = {
    // RECORDORG_TYPE: [],  // 备案机构
    TERM_TYPE: [],   // 产品类别
    // LINK_PRINCIPAL_NO: [],   // 受托人
    // TRUSTEE: [],   // 托管人
    MANAGER: [],    // 账管人
    AREA: [],   // 所属地区
    OTHER_INVESTOR: [],  // 其他投资管理人、移交投管人
    EMISSION_WAY: [],  // 发行方式
    OLDAGE_PRODUCT_TYPE: []
  };
  // 年金基础信息
  public annuityAddOrEditBody: any = {
    // sRecordorgType: '',
    // sTermType: '',
    sIsAssetTransfer: '0',
    // sLinkPrincipalNo: '',
    // sManager: '',
    // sArea: '',
    // sOtherInvestor: '',
    // sInvestor: '',
    sIsContainRight: '',//是否含权
    // sManagerNo: '',//投资经理
    // sProjectManager: '',//项目经理
    sIsRenewal: '',//是否自动续约
    // sProductType:''//产品类型(下拉框)
  }

  constructor(
    public router: Router,
    private route: ActivatedRoute,
    public annuityInfoService: InfoService,
    public dataService: DataService
  ) {
    let that = this;
    this.route.params.subscribe((data: any) => {
      this.nFundNo = data.nFundNo;
      this.operate = data.operate;
      this.index = data.index;
      if (this.operate == 'edit') {
        this.oldProGetSingleProduct(this.nFundNo);
      }
    });
  }
  ngOnInit() {
    // 多选下拉框
    window['$'](".select2").select2();
    // 获取字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    this.getDictionary();
    // 获取托管人数据
    // this.bankDictionaryList = JSON.parse(localStorage.getItem("bankDictionaryList"));
    // 基金经理下拉框
    this.LoadManagerList();
    // 项目经理下拉框
    this.LoadProjectManagerList();
  }
  ngAfterViewInit() {
    let that = this;
    if (this.operate != 'edit') {
      this.loadSelect();
    }
    // 运作日期、终止日期
    if (this.index == 'not-running' || this.index == 'new') {
      window['$']('#dBegin').attr("disabled", "disabled");
      window['$']('#dBegin').css("background", "#eeeeee");
      window['$']('#dStop').attr("disabled", "disabled");
      window['$']('#dStop').css("background", "#eeeeee");
    } else if (this.index == 'running') {
      window['$']('#dBegin').attr("disabled", false);
      window['$']('#dBegin').css("background", "#ffffff");
      window['$']('#dStop').attr("disabled", "disabled");
      window['$']('#dStop').css("background", "#eeeeee");
    } else {
      window['$']('#dBegin').attr("disabled", false);
      window['$']('#dBegin').css("background", "#ffffff");
      window['$']('#dStop').attr("disabled", false);
      window['$']('#dStop').css("background", "#ffffff");
    }
  }
  // 加载下拉框
  loadSelect() {
    let that = this;
    // setTimeout(function () {
    // 备案机构
    // window['$']('#sRecordorgTypeSelected').select2({ width: '240px' });
    // window['$']('#sRecordorgTypeSelected').on("select2:select", function (e) {
    //   that.annuityAddOrEditBody.sRecordorgType = window['$']('#sRecordorgTypeSelected').select2("val");
    // })
    // 期限
    window['$']('#sTermTypeSelected').select2({ width: '240px' });
    window['$']('#sTermTypeSelected').on("select2:select", function (e) {
      that.annuityAddOrEditBody.sTermType = window['$']('#sTermTypeSelected').select2("val");
      // 到期日计算
      if (that.annuityAddOrEditBody.dEffective == '' || that.annuityAddOrEditBody.dEffective == null) {
        that.annuityAddOrEditBody.sTermType = '';
      } else {
        if (that.annuityAddOrEditBody.sTermType == '' || that.annuityAddOrEditBody.sTermType == null) {
          that.annuityAddOrEditBody.dEnd = '';
        } else if (that.annuityAddOrEditBody.sTermType == '0') {
          that.annuityAddOrEditBody.dEnd = '';
          window['$']("#dEnd").attr("disabled", "disabled");
          window['$']("#dEnd").css("background", "#eee");
        } else {
          window['$']("#dEnd").removeAttr("disabled");
          window['$']("#dEnd").css("background", "white");
          that.annuityAddOrEditBody.dEnd = Util.dateIncrease(that.annuityAddOrEditBody.dEffective, that.annuityAddOrEditBody.sTermType);
        }
      }
    })
    // 受托人
    // window['$']('#sLinkPrincipalNoSelected').select2({ width: '240px' });
    // window['$']('#sLinkPrincipalNoSelected').on("select2:select", function (e) {
    //   that.annuityAddOrEditBody.sLinkPrincipalNo = window['$']('#sLinkPrincipalNoSelected').select2("val");
    // })
    // 账管人
    // window['$']('#sManagerSelected').select2({ width: '240px' });
    // window['$']('#sManagerSelected').on("select2:select", function (e) {
    //   that.annuityAddOrEditBody.sManager = window['$']('#sManagerSelected').select2("val");
    // })
    // 托管人
    window['$']('#sTrusteeSelected').select2({ width: '240px', tags: true });
    window['$']('#sTrusteeSelected').on("select2:select", function (e) {
      that.annuityAddOrEditBody.sTrustee = window['$']('#sTrusteeSelected').select2("val");
    })
    // 投资经理
    // window['$']('#sManagerNoSelected').select2({ width: '240px' });
    // window['$']('#sManagerNoSelected').on("select2:select", function (e) {
    //   that.annuityAddOrEditBody.sManagerNo = window['$']('#sManagerNoSelected').select2("val");
    // })
    // 所属地区
    // window['$']('#sAreaSelected').select2({ width: '240px' });
    // window['$']('#sAreaSelected').on("select2:select", function (e) {
    //   that.annuityAddOrEditBody.sArea = window['$']('#sAreaSelected').select2("val");
    // })
    // 产品类型
    window['$']('#sProductTypeSelected').select2({ width: '240px' });
    window['$']('#sProductTypeSelected').on("select2:select", function (e) {
      that.annuityAddOrEditBody.sProductType = window['$']('#sProductTypeSelected').select2("val");
    })
    // }, 300);
  }
  // 查询单个产品基础信息
  oldProGetSingleProduct(nFundNo) {
    let that = this;
    new Promise((resolve, reject) => {
      this.annuityInfoService.GetSingleProduct(nFundNo).subscribe(data => {
        if (data) {
          that.annuityAddOrEditBody = data;
          // 移交投管人、其他投资管理人、项目经理转换
          // that.sInvestorSelectList = _.split(data.sInvestor, ',');
          // that.investorSelectList = _.split(data.sOtherInvestor, ',');
          that.managerSelectList = _.split(data.sProjectManager, ',');
          if (that.annuityAddOrEditBody.sArea == null) {
            that.annuityAddOrEditBody.sArea = '';
          }
          // 用于关联附件受托人
          that.dataService.sLinkPrincipalNo = data.sLinkPrincipalNo;
          that.dataService.ZhInfo = data;
          _.forEach(this.dictionaryList.LINK_PRINCIPAL_NO, (item) => {
            if (item.sItemKey == data.sLinkPrincipalNo) {
              that.dataService.sLinkPrincipal = item.sItemValue
            }
          })
          resolve(data);
        }
      })
    }).then(data => {
      //判断期限是否为固定期限
      if (that.annuityAddOrEditBody.sTermType == '0') {
        that.annuityAddOrEditBody.dEnd = '';
        window['$']('#dEnd').attr("disabled", "disabled");
        window['$']('#dEnd').css("background", "#eeeeee");
      }
      // 所属地区
      // if (that.annuityAddOrEditBody.sArea != '' && that.annuityAddOrEditBody.sArea != null && that.annuityAddOrEditBody.sArea != undefined) {
      //   that.area = _.cloneDeep(that.annuityAddOrEditBody.sArea.split(',')[0]);
      // }
      //控制移交托管人是否可选
      // this.IsAssetTransfer();
      // 重加载一次，防止数据不显示
      setTimeout(function () {
        window['$'](".manager-select").select2();
        that.loadSelect();
      }, 1);
    })
  }
  // 一对多新增或编辑产品
  otmAddOrEditBasicInfo(type) {
    let that = this;
    this.annuityAddOrEditBody.sFundType = '5';
    this.annuityAddOrEditBody.sProjectManager = Util.transferValue('.manager-select');
    // this.annuityAddOrEditBody.sInvestor = this.ctrlsInvestor();
    // this.annuityAddOrEditBody.sOtherInvestor = this.ctrlInvestorId();
    // this.annuityAddOrEditBody.sProjectManager = this.ctrlManagerId();
    let ProductAudit = that.annuityAddOrEditBody.sProductAudit;
    if (this.requireAdd()) {
      window["swal"]({
        title: "提示",
        text: "是否确定保存基础信息?",
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        showCancelButton: true,
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      }, function (isConfirm) {
        if (isConfirm) {
          if (type == 'add') {
            let publicUrl: any = { "url": "/pages/oldageProduct/new/detail/add" };
            that.annuityAddOrEditBody.sStatusRunning = "1";
            that.annuityInfoService.oldProAddProduct(that.annuityAddOrEditBody).subscribe(data => {
              if (data) {
                that.router.navigate(['/pages/oldageProductList/not-running']);
                that.dataService.public_url.emit(publicUrl);
                window['swal']("成功", "新增成功!", "success");
              }
            });
          } else if (type == 'edit') {
            that.annuityInfoService.oldProEditProduct(that.annuityAddOrEditBody).subscribe(data => {
              if (data) {
                if (ProductAudit == '1') {
                  window['swal']("成功", "请等待产品审核!", "success");
                } else {
                  window['swal']("成功", "保存成功!", "success");
                }
              }
            })
          }
        }
      })
    }
  }
  // 是否资产移交控制
  // IsAssetTransfer() {
  //   let that = this;
  //   if (that.annuityAddOrEditBody.sIsAssetTransfer == '0') {
  //     that.annuityAddOrEditBody.sInvestor = "";
  //     window['$']('.sInvestor-select').select2("val", '--请选择--'); // 移交投管人
  //   }
  // }
  // 新增、编辑必填校验
  requireAdd() {
    let that = this;
    let requiredAddTip = [];
    let sFullName = _.trim(this.annuityAddOrEditBody.sFullName);
    let sContractName = _.trim(this.annuityAddOrEditBody.sContractName);
    let sIsAssetTransfer = _.trim(this.annuityAddOrEditBody.sIsAssetTransfer);
    let sInvestor = _.trim(this.annuityAddOrEditBody.sInvestor);
    if (sFullName == "" || sFullName == null) {
      requiredAddTip.push("产品名称");
    }
    if (sContractName == "" || sContractName == null) {
      requiredAddTip.push("合同名称");
    }
    // if (sIsAssetTransfer == "" || sIsAssetTransfer == null) {
    //   requiredAddTip.push("是否资产移交");
    // }
    // if (sIsAssetTransfer == "1" && sInvestor == "" || sInvestor == null) {
    //   requiredAddTip.push("移交投管人");
    // }
    if (requiredAddTip.length > 0) {
      let requiredAddTips = requiredAddTip.join("、");
      window['swal']("提示", "请填写:" + requiredAddTips, "warning");
      return false;
    } else {
      return true;
    }
  }
  // 到期日计算
  termContrl() {
    if (this.annuityAddOrEditBody.sTermType != null && this.annuityAddOrEditBody.sTermType != '' && this.annuityAddOrEditBody.sTermType != '0' && (this.annuityAddOrEditBody.dEffective != '' && this.annuityAddOrEditBody.dEffective != null)) {
      this.annuityAddOrEditBody.dEnd = Util.dateIncrease(this.annuityAddOrEditBody.dEffective, this.annuityAddOrEditBody.sTermType);
      window['$']('#dEnd').removeAttr("disabled");
      window['$']('#dEnd').css("background", "white");
    } else if (this.annuityAddOrEditBody.sTermType == '0') {
      this.annuityAddOrEditBody.dEnd = '';
      window['$']('#dEnd').attr("disabled", "disabled");
      window['$']('#dEnd').css("background", "#eeeeee");
    } else if (this.annuityAddOrEditBody.sTermType == '') {
      window['$']('#dEnd').removeAttr("disabled");
      window['$']('#dEnd').css("background", "white");
    }
  }

  //获取基金经理下拉框数据
  LoadManagerList() {
    let that = this;
    that.annuityInfoService.getManagerList().subscribe(data => {
      if (data) {
        that.ManagerList = data;
      }
    });
  }
  //获取基金经理下拉框数据
  LoadProjectManagerList() {
    let that = this;
    that.annuityInfoService.getProjectManagerList().subscribe(data => {
      if (data) {
        that.ProjectManagerList = data;
      }
    });
  }
  //计算字符串字符长度
  mathStringLength(item) {
    this.realLength = Util.mathStringLength(item)
  }
  // 移交投管人sInvestor
  // ctrlsInvestor() {
  //   let investorList: any;
  //   let investorChecked = [];
  //   let selected = window['$']('.sInvestor-select').val();
  //   _.forEach(selected, item => {
  //     let index1 = item.indexOf("'");
  //     let index2 = item.lastIndexOf("'");
  //     let sales = item.substring(index1 + 1, index2);
  //     investorChecked.push(sales);
  //   })
  //   investorList = investorChecked.join(",");
  //   return investorList;
  // }
  // 其他投资管理人
  // ctrlInvestorId() {
  //   let investorIdList: any;
  //   let investorChecked = [];
  //   let selected = window['$']('.investor-select').val();
  //   console.info(selected)
  //   _.forEach(selected, item => {
  //     let index1 = item.indexOf("'");
  //     let index2 = item.lastIndexOf("'");
  //     let sales = item.substring(index1 + 1, index2);
  //     investorChecked.push(sales);
  //   })
  //   investorIdList = investorChecked.join(",");
  //   return investorIdList;
  // }
  // 项目经理
  ctrlManagerId() {
    let managerIdList: any;
    let managerChecked = [];
    let selected = window['$']('.manager-select').val();
    _.forEach(selected, item => {
      let index1 = item.indexOf("'");
      let index2 = item.lastIndexOf("'");
      let sales = item.substring(index1 + 1, index2);
      managerChecked.push(sales);
    })
    managerIdList = managerChecked.join(",");
    return managerIdList;
  }
  // OnAreaChg(event) {
  //   if (event[1] == '--请选择--' && event[0] != '--请选择--') {
  //     this.annuityAddOrEditBody.sArea = this.annuityAddOrEditBody.sArea + ',' + event[0]
  //   } else if (event[0] == '--请选择--') {
  //     this.annuityAddOrEditBody.sArea = '';
  //   } else {
  //     this.annuityAddOrEditBody.sArea = this.annuityAddOrEditBody.sArea + ',' + event[0] + "-" + event[1]
  //   }
  // }
  // OnAreaCodeChg(event) {
  //   this.annuityAddOrEditBody.sArea = event;
  // }
  // 获取备案机构、受托人、托管人下拉框值
  getDictionary() {
    let that = this;
    this.annuityInfoService.getDictionary().subscribe(data => {
      if (data) {
        that.distionary.RECORDORG_TYPE = data.RECORDORG_TYPE;
        that.distionary.LINK_PRINCIPAL_NO = data.LINK_PRINCIPAL_NO;
        that.distionary.TRUSTEE = data.TRUSTEE;
      }
    })
  }
}
